//
//  QAUtil.m
//  Rong360
//
//  Created by tianliwei on 13/3/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//

#import "RequestUtil.h"
#import "ParseUtil.h"
@implementation RequestUtil

+ (void)requestWithType:(RequestType)type Url:(NSString *)url{
    NSURL *_url = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *_request = [NSMutableURLRequest requestWithURL:_url cachePolicy:NSURLRequestReloadRevalidatingCacheData timeoutInterval:15];
    [NSURLConnection sendAsynchronousRequest:_request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) {
                               //block define statment
                               NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                               NSLog(@"response status code is %d",[httpResponse statusCode]);
                               if (error) {
                                   
                                   NSLog(@"%@",error);//从缓存获取
                                   if (type == Product){
                                       [[ParseUtil shareParser]getProductInfoFromCache];
                                   }
                                   
                               }else if ([data length] == 0 && error == nil){
                                   
                                   NSLog(@"=========No data========");
                                   //没有数据
                                   
                               }else{
                                   
                                   if (type == Question) {
                                       
                                       [[ParseUtil shareParser]getQuestionFeedback:data];
                                   }else if (type == Answer){
                                       [[ParseUtil shareParser]getReply:data];
                                   }else if (type == Product){
                                       [[NSUserDefaults standardUserDefaults]setObject:data forKey:kProductInfo];//保存数据
                                       [[ParseUtil shareParser]getProductInfo:data];
                                   }else if (type == Recommend){
                                       [[NSUserDefaults standardUserDefaults]setObject:data forKey:kRecommendInfo];//保存数据
                                       [[ParseUtil shareParser]getRecommendInfo:data];
                                   }
                               }
                               
                           }];
}

@end
